package com.gitee.feizns.message.web.server;

import com.alibaba.fastjson.JSONObject;
import com.gitee.feizns.message.domain.ao.FaMessage;
import com.gitee.feizns.message.domain.vo.FvMessage;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author feizns
 * @since 2019/6/2 0002
 */
@ServerEndpoint("/socket")
@Component
public class WebSocketServer {

    private static final Map<String, WebSocketServer> WEB_SOCKET_SERVER_MAP = new ConcurrentHashMap<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        WEB_SOCKET_SERVER_MAP.put(session.getId(), this);
        sendAllMessage(createFv("欢迎" + session.getId() + "加入.", "系统"));
    }

    @OnClose
    public void onClose() {
        String id = session.getId();
        WEB_SOCKET_SERVER_MAP.remove(id);
        sendAllMessage(createFv(id + "退出了.", "系统"));
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        if ( message != null ) {
            FaMessage faMessage = JSONObject.parseObject(message, FaMessage.class);
            if ( faMessage != null ) {
                if ( faMessage.getToIds() != null && faMessage.getToIds().length != 0 ) {

                    sendMessage(createFv(faMessage.getContent(), session.getId()));

                    for (String id : faMessage.getToIds()) {
                        WebSocketServer server = WEB_SOCKET_SERVER_MAP.get(id);
                        if ( server != null )
                            server.sendMessage(server.createFv(faMessage.getContent(), session.getId()));
                    }
                } else {
                    sendAllMessage(createFv(faMessage.getContent(), session.getId()));
                }
            }
        }
    }

    private FvMessage createFv(String content, String from) {
        String sessionId = this.session.getId();
        String[] otherIds = WEB_SOCKET_SERVER_MAP.keySet().stream().filter(key -> key.equals(sessionId) == false).toArray(String[]::new);
        return new FvMessage().setContent(content).setFrom(from).setSessionId(sessionId).setOtherIds(otherIds);
    }

    /**
     * @param message
     */
    public void sendMessage(FvMessage message) {
        this.session.getAsyncRemote().sendText(JSONObject.toJSONString(message));
    }

    public void sendAllMessage(FvMessage message) {
        for (WebSocketServer server : WEB_SOCKET_SERVER_MAP.values()) {
            server.sendMessage(server.createFv(message.getContent(), message.getFrom()));
        }
    }

}
